package com.yint.browser;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * 浏览器WebView
 *
 * @author yintian
 */
public class BrowserWebView extends WebView {

    private final String TAG = "BrowserWebView";

    private String pageTitle;

    private CustomViewExhibitor customViewExhibitor;

    public BrowserWebView(Context context) {
        this(context, null);
    }

    public BrowserWebView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BrowserWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        Log.d(TAG, "init");
        setWebViewClient(webViewClient);
        setWebChromeClient(webChromeClient);
//        setOnKeyListener(onKeyListener);
        updateWebSettings();
    }

    private void updateWebSettings() {
        WebSettings webSettings = getSettings();
        webSettings.setJavaScriptEnabled(true); // 是否开启JS支持
        webSettings.setPluginState(WebSettings.PluginState.ON_DEMAND);
//        webSettings.setPluginsEnabled(true); // 是否开启插件支持
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); // 是否允许JS打开新窗口
        webSettings.setUseWideViewPort(true); // 缩放至屏幕大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕大小
        webSettings.setSupportZoom(true); // 是否支持缩放
        webSettings.setBuiltInZoomControls(true); // 是否支持缩放变焦，前提是支持缩放
        webSettings.setDisplayZoomControls(true); // 是否隐藏缩放控件
        webSettings.setSupportMultipleWindows(true);//是否支持多窗口
        webSettings.setAllowFileAccess(true); // 是否允许访问文件
        webSettings.setDatabaseEnabled(true); // 是否数据缓存
        webSettings.setAppCacheEnabled(true); // 是否应用缓存
        webSettings.setDomStorageEnabled(true); // 是否节点缓存
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);// 设置缓存模式,一共有四种模式
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);//支持内容重新布局,一共有四种方式
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

        // 设置默认字体大小
//        webSettings.setMediaPlaybackRequiresUserGesture(false); // 是否要手势触发媒体
//        webSettings.setStandardFontFamily("sans-serif"); // 设置字体库格式
//        webSettings.setFixedFontFamily("monospace"); // 设置字体库格式
//        webSettings.setSansSerifFontFamily("sans-serif"); // 设置字体库格式
//        webSettings.setSerifFontFamily("sans-serif"); // 设置字体库格式
//        webSettings.setCursiveFontFamily("cursive"); // 设置字体库格式
//        webSettings.setFantasyFontFamily("fantasy"); // 设置字体库格式
        webSettings.setTextZoom(100); // 设置文本缩放的百分比
//        webSettings.setMinimumFontSize(8); // 设置文本字体的最小值(1~72)
//        webSettings.setDefaultFontSize(16); // 设置文本字体默认的大小

//        webSettings.setLoadsImagesAutomatically(false); // 是否自动加载图片
        webSettings.setDefaultTextEncodingName("UTF-8"); // 设置编码格式
        webSettings.setNeedInitialFocus(true); // 是否需要获取焦点
        webSettings.setGeolocationEnabled(true); // 设置开启定位功能
//        webSettings.setBlockNetworkLoads(false); // 是否从网络获取资源
    }

    public String getPageTitle() {
        return pageTitle;
    }

    public void setCustomViewExhibitor(CustomViewExhibitor customViewExhibitor) {
        this.customViewExhibitor = customViewExhibitor;
    }

    private final WebViewClient webViewClient = new WebViewClient() {
        private String startUrl;

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            startUrl = url;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            String url = request.getUrl().toString();
            Log.d(TAG, "webViewClient shouldOverrideUrlLoading url:" + url);
            Log.d(TAG, "webViewClient shouldOverrideUrlLoading startUrl:" + startUrl);
            if (URLUtil.isNetworkUrl(url) || URLUtil.isFileUrl(url)) {
                //防止重定向导致的goback()方法无法正常使用
                if (startUrl != null && startUrl.equals(url)) {
                    Log.d(TAG, "webViewClient shouldOverrideUrlLoading view.loadUrl");
                    view.loadUrl(url);
                    return true;
                }
                //重定向交给系统处理
                return super.shouldOverrideUrlLoading(view, request);
            } else {
                Log.d(TAG, "webViewClient shouldOverrideUrlLoading startActivity:Intent.ACTION_VIEW");
                try {
                    getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.d(TAG, "webViewClient shouldOverrideUrlLoading err:" + e);
                }
                return true;
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            pageTitle = view.getTitle();
        }
    };

    private final WebChromeClient webChromeClient = new WebChromeClient() {
        // 全屏的时候调用
        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            Log.d(TAG, "webChromeClient onShowCustomView");
            super.onShowCustomView(view, callback);
            if (customViewExhibitor != null) {
                customViewExhibitor.onShowCustomView(view, callback);
            }
        }

        // 切换为竖屏的时候调用
        @Override
        public void onHideCustomView() {
            Log.d(TAG, "webChromeClient onHideCustomView");
            super.onHideCustomView();
            if (customViewExhibitor != null) {
                customViewExhibitor.onHideCustomView();
            }
        }
    };

    private void clear() {
        destroy();
        clearCache(true);
        clearFormData();
        clearMatches();
        clearSslPreferences();
        clearDisappearingChildren();
        clearHistory();
        //clearView();
        clearAnimation();
        loadUrl("about:blank");
        removeAllViews();
    }

    @Override
    public void destroy() {
        super.destroy();
        clear();
    }

    private final OnKeyListener onKeyListener = new OnKeyListener() {
        @Override
        public boolean onKey(View view, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_BACK && canGoBack()) { // 表示按返回键 时的操作
                    goBack(); // 后退
                    return true; // 已处理
                }
            }
            return false;
        }
    };

    //自定义视图展示接口
    public interface CustomViewExhibitor {
        void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback);

        void onHideCustomView();
    }
}
